
// 商品仓储
package sale
import (
    "fmt"
	"time"
	"errors"
	"strings"
	"strconv"
	"dhfshop/models"
	"dhfshop/models/consts"
	"github.com/astaxie/beego/orm"
)

// goods是商品的普通说法，表示用来卖的商品。item是在某个单子或列表中的商品可以这么称呼
type Sku struct {
    PartnerId     int64   `orm:"column(partner_id)" json:"partner_id" form:"partner_id"`       //
	StoreId       int64   `orm:"column(store_id)" json:"store_id" form:"store_id"`
	SkuId         int64   `orm:"column(sku_id);pk" json:"-" form:"-"`
	SkuIdStr      string  `orm:"-" json:"sku_id" form:"sku_id"`
	Item          *Item   `orm:"column(item_id);rel(fk);on_delete(cascade)" json:"-" ` 
    ItemId        string  `orm:"-" json:"item_id" form:"item_id"`
	ImgUrl        string  `orm:"column(imgurl);null" json:"imgurl" form:"imgurl"`   /*规格图片链接*/
	Barcode       string  `orm:"column(barcode);size(32);index" json:"barcode"`     /*SKU条形码,暂设置index,以后设置unique*/
	SkuOuterId    string  `orm:"column(sku_outer_id);null" json:"sku_outer_id" form:"sku_outer_id"` /*SKU外部ID */
	SkuProperties string  `orm:"column(sku_properties);null" json:"sku_properties" form:"sku_properties"` /*sku 属性*/
	SkuPrice      float32 `orm:"column(sku_price);digits(12);decimals(2)" json:"sku_price" form:"sku_price"`  /*sku 价格 */
	SkuStocks     int32   `orm:"column(sku_stocks)" json:"sku_stocks" form:"sku_stocks"`  /* sku 库存 */
	StatusId      int32   `orm:"column(status_id);default(1)" json:"status_id" form:"status_id"`  /* 状态：1 正常、2 删除 */
	TaxRate       float32 `orm:"column(tax_rate);digits(12);decimals(2)" json:"tax_rate" form:"tax_rate"` //税率
}

type Item struct {
	PartnerId   int64    `orm:"column(partner_id)" json:"partner_id" form:"partner_id"`       //
    StoreId     int64    `orm:"column(store_id)" json:"store_id" form:"store_id"`        /* 店铺ID */
	PItemId     int64    `orm:"column(p_item_id);default(0)" json:"-" form:"-"` 
    PItemIdStr  string   `orm:"-" json:"p_item_id" form:"p_item_id"`                    //父商品id
	ItemId      int64    `orm:"column(item_id);pk" json:"-" form:"-"` 
    ItemIdStr   string   `orm:"-" json:"item_id" form:"item_id"`
	CategoryId  int64    `orm:"column(category_id)" json:"category_id" form:"category_id"`             /*  */
	TypeId      int      `orm:"column(type_id)" json:"type_id" form:"type_id"`       /* 1: 分销; 2: 自有商品 */
    DateRelated int      `orm:"column(date_related)" json:"date_related" form:"date_related"`  /*是否和日期相关*/
	Pid         int64    `orm:"column(pid);index" json:"pid" form:"pid"`             /* 如果是分销产品,分销ID  */
	Title       string   `orm:"column(title);size(128);null" json:"title" form:"title"` /*  */
	OuterId     string   `orm:"column(outer_id);size(128);null" json:"outer_id" form:"outer_id"` /*货号*/
	Barcode     string   `orm:"column(barcode);size(32)" json:"barcode" form:"barcode"`   /*条码*/  
	Image       string   `orm:"column(img);size(256);null" json:"img" form:"img"`           /* */
	Img1        string   `orm:"column(img1);null" json:"img1" form:"img1"`           /* */
	Img2        string   `orm:"column(img2);null" json:"img2" form:"img2"`           /* */
	Img3        string   `orm:"column(img3);null" json:"img3" form:"img3"`           /* */
	Img4        string   `orm:"column(img4);null" json:"img4" form:"img4"`           /* */
	Img5        string   `orm:"column(img5);null" json:"img5" form:"img5"`           /* */
	Img6        string   `orm:"column(img6);null" json:"img6" form:"img6"`           /* */
	Img7        string   `orm:"column(img7);null" json:"img7" form:"img7"`           /* */
	Img8        string   `orm:"column(img8);null" json:"img8" form:"img8"`           /* */
	Img9        string   `orm:"column(img9);null" json:"img9" form:"img9"`           /* */
	Cost        float32  `orm:"column(cost);digits(12);decimals(2)" json:"cost" form:"cost"` /* 成本价 */
	Price       float32  `orm:"column(price);digits(12);decimals(2)" json:"price" form:"price"` /* 定价*/
	MaketPrice  float32  `orm:"column(maket_price);digits(12);decimals(2)" json:"maket_price" form:"maket_price"` /* 市场价*/
	PromPrice   float32  `orm:"column(prom_price);digits(12);decimals(2)" json:"prom_price" form:"prom_price"` /* 促销价 */
	PackingFee  float32  `orm:"column(packing_fee);digits(12);decimals(2)" json:"packing_fee" form:"packing_fee"` /* 包装费 */
	ApplySubs   string   `orm:"column(apply_subs);null" json:"apply_subs" form:"apply_subs"`        /*  */
    LimitPay    string   `orm:"column(limit_pay);null" json:"limit_pay" form:"limit_pay"`  /*支付限制:no_balance(不接受余额支付),no_credit(不接受信用卡支付) */
	Note        string   `orm:"column(note);size(256);null" json:"note" form:"note"`            /* 简单备注,如:(限时促销) */
    Description string   `orm:"column(description);type(text);null" json:"description" form:"description"` /* */
	OnShelves   int32    `orm:"column(on_shelves);default(0)" json:"on_shelves" form:"on_shelves"`/* 是否上架,1为上架 0为下架(缺省) */
    IsPresent     int      `orm:"column(is_present);null" json:"is_present" form:"is_present"`  /* 是否为赠品 */
	PromotionFlag int      `orm:"column(prom_flag);null" json:"prom_flag" form:"prom_flag"`     /* 促销标志 */
    IsInclPostage int      `orm:"column(is_incl_postage);default(2)" json:"is_incl_postage" form:"is_incl_postage"` //是否包邮:1=是 2=否
	FareId        int64    `orm:"column(fare_id)" json:"fare_id" form:"fare_id"`             /* 运费模板ID */
    Weight        float32  `orm:"column(weight);digits(12);decimals(2)" json:"weight" form:"weight"`    /* 商品重量 */
	StockNum      int32    `orm:"column(stock_num)" json:"stock_num" form:"stock_num"`          /* 库存 */
	SaleNum       int      `orm:"column(sale_num);default(0)" json:"sale_num" form:"sale_num"`        /* 已售件数 */
	DeliveryAddrs string   `orm:"column(delivery_addrs);type(text);null" json:"delivery_addrs" form:"delivery_addrs"` /*发货地址列表 */
	StatusId      int32    `orm:"column(status_id);default(1)" json:"status_id" form:"status_id"`     /* 状态：1 正常、2 删除 */
	CreatedAt     time.Time   `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"` 
	CreatedAtStr  string      `orm:"-" json:"created_at" form:"-"`
    UpdatedAt     time.Time   `orm:"auto_now;column(updated_at);type(datetime)" json:"-" form:"-"`         
	UpdatedAtStr  string      `orm:"-" json:"updated_at" form:"-"`
	Skus         []*Sku    `orm:"reverse(many)" json:"skus,omitempty" form:"-"`           /* 反向关系,用来表述ORM存储关系和组合JSON输出*/
	SkuJson      string    `orm:"-" json:"-" form:"skus"`                       /* 临时存放上传的订单sku*/
	TagIds       string   `orm:"column(tag_ids);size(250);null" json:"tag_ids" form:"tag_ids"` /*标签ID列表,逗号分隔*/
	VDesc        string   `orm:"column(vdesc);type(text);null" json:"vdesc" form:"vdesc"` /*商品描述虚拟字段*/
	Xtype    int32 `orm:"column(xtype);default(0)" json:"xtype" form:"xtype"` /*0普通商品;1海淘商品;2….后续再扩展*/
	IsVirtual   bool     `orm:"column(is_virtual);default(false)" json:"is_virtual" form:"is_virtual"`     /*是否虚拟商品*/
	Sort      int      `orm:"column(sort);default(0)" json:"sort" form:"sort"`          /*排序字段*/
}

func init() {
    orm.RegisterModel(new(Item),new(Sku))   
}

func AddItem(m *Item) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetItemByItemId(id int64) (v *Item, err error) {
	o := models.GetDefaultDB()
	v = &Item{ItemId: id}
	if err = o.Read(v); err == nil {
	    v.ItemIdStr = strconv.FormatInt(v.ItemId, 10)
		v.PItemIdStr = strconv.FormatInt(v.PItemId, 10)
		v.CreatedAtStr = v.CreatedAt.Format(consts.DATETIME_FORMAT)
		v.UpdatedAtStr = v.UpdatedAt.Format(consts.DATETIME_FORMAT)
		o.LoadRelated(v, "Skus")
		for _, sku := range v.Skus {
			sku.SkuIdStr = strconv.FormatInt(sku.SkuId, 10)
			sku.ItemId = strconv.FormatInt(sku.Item.ItemId, 10)
			sku.Item = nil
		}
		return v, nil
	}
	return nil, err
}

func GetValidItemByItemId(id int64) (v *Item, err error) {
	o := models.GetDefaultDB()
	v = &Item{ItemId:id,OnShelves:1,StatusId:1}
	if err = o.Read(v, "ItemId", "OnShelves", "StatusId"); err == nil {
	    o.LoadRelated(v, "Skus")
		for _, sku := range v.Skus {
			sku.Item = nil
		}
		v.CreatedAtStr = v.CreatedAt.Format(consts.DATETIME_FORMAT)
		v.UpdatedAtStr = v.UpdatedAt.Format(consts.DATETIME_FORMAT)
		return v, nil
	}
	return nil, err
}


func GetPackItems(categoryId, itemId int64) (items []*Item, err error) {
	items = []*Item{}
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Item))
	if categoryId > 0 {
	   qs = qs.Filter("category_id", categoryId)
	}
	if itemId > 0 {
	   qs = qs.Filter("item_id", itemId)
	}
	if _, err = qs.All(&items); err == nil {
	    for _, item := range items {
			item.ItemIdStr = strconv.FormatInt(item.ItemId, 10)
			item.PItemIdStr = strconv.FormatInt(item.PItemId, 10)
			item.CreatedAtStr = item.CreatedAt.Format(consts.DATETIME_FORMAT)
			item.UpdatedAtStr = item.UpdatedAt.Format(consts.DATETIME_FORMAT)
		}
	}
	return
}

func GetItemByOuterId(outerId string) (v *Item, err error) {
	o := models.GetDefaultDB()
	v = &Item{OuterId: outerId}
	if err = o.Read(v, "OuterId"); err == nil {
		return v, nil
	}
	return nil, err
}

func GetItemByPid(pid int64) (v *Item, err error) {
	o := models.GetDefaultDB()
	v = &Item{Pid: pid}
	if err = o.Read(v, "Pid"); err == nil {
		return v, nil
	}
	return nil, err
}

func GetItemByMulti(itemId int64, outerId, barcode string) (item *Item, err error) {
	item = &Item{}
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Item))
	if itemId > 0 {
	   qs = qs.Filter("item_id", itemId)
	}
	if len(outerId) > 0 {
	   qs = qs.Filter("outer_id", outerId)
	}
	if len(barcode) > 0 {
	   qs = qs.Filter("barcode", barcode)
	}
	err = qs.One(item)
	return
}

func GetOpenApiStocks(partnerId,storeId int64,itemId,start,end string,offset,limit int)([]*Item,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Item))
	qs = qs.Filter("partner_id", partnerId)
	if storeId > 0 {
	    qs = qs.Filter("store_id", storeId)
	}
	if len(itemId) > 0 {
	    if tmp, err := strconv.ParseInt(itemId, 10, 64); err == nil {
		    qs = qs.Filter("item_id", tmp)
		}
	}
	if startTime, err := time.Parse(consts.DATETIME_FORMAT, start); err == nil {
		qs = qs.Filter("created_at__gte", startTime)
	}
	if endTime, err := time.Parse(consts.DATETIME_FORMAT, end); err == nil {
		qs = qs.Filter("created_at__lte", endTime)
	}
	cnt, err := qs.Count()
	qs = qs.OrderBy("created_at")
	var lists []*Item
	if _, err = qs.Limit(limit, offset).All(&lists); err == nil {
	    for _, item := range lists {
			item.ItemIdStr = strconv.FormatInt(item.ItemId, 10)
			item.CreatedAtStr = item.CreatedAt.Format(consts.DATETIME_FORMAT)
			item.UpdatedAtStr = item.UpdatedAt.Format(consts.DATETIME_FORMAT)
			o.LoadRelated(item, "Skus")
			for _, sku := range item.Skus {   
			    sku.SkuIdStr = strconv.FormatInt(sku.SkuId, 10)
				sku.ItemId = strconv.FormatInt(sku.Item.ItemId, 10)
				sku.Item = nil
		    }
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateItemByItemId(m *Item, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := Item{ItemId: m.ItemId}
	if err = o.Read(&v); err == nil {
		if _, err = o.Update(m, k...); err != nil {
			return err
		}
	}
	return
}

func UpdateItemByOuterId(m *Item, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := Item{OuterId: m.OuterId}
	if err = o.Read(&v, "OuterId"); err == nil {
		var num int64
		if num, err = o.Update(m, k...); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

func GetAllItems(storeIds []int64,query map[string]string,itemIdArr,fields []string,order_by map[string]string,offset,limit int)([]*Item, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Item))
	if start, ok := query["start_created"]; ok {
		if startTime, err := time.Parse(consts.DATELINKTIME_FORMAT, start); err == nil {
		    qs = qs.Filter("created_at__gte", startTime)
		}
		delete(query, "start_created")
	}
	if end, ok := query["end_created"]; ok {
		if endTime, err := time.Parse(consts.DATELINKTIME_FORMAT, end); err == nil {
	        qs = qs.Filter("created_at__lte", endTime)
	    }
		delete(query, "end_created")
	}
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		if ok := strings.Contains(v, "|"); ok {
		    valueArr := strings.Split(v, "|")
			qs = qs.Filter(k, valueArr)
		} else {
		    if ok := strings.Contains(k, "created_at"); ok {
				if createTime, err := time.Parse(consts.DATETIME_FORMAT, v); err == nil {
					qs = qs.Filter(k, createTime)
				}
			} else {
				qs = qs.Filter(k, v)
			}
		}	
	}
	if len(itemIdArr) > 0 {
	    qs = qs.Filter("item_id__in", itemIdArr)
	}
	if len(storeIds) > 0 {
        qs = qs.Filter("store_id__in", storeIds)
    }
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*Item
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
	    for _, item := range lists {
			o.LoadRelated(item, "Skus")
			for _, sku := range item.Skus {   
			    sku.SkuIdStr = strconv.FormatInt(sku.SkuId, 10)
				sku.ItemId = strconv.FormatInt(sku.Item.ItemId, 10)
				sku.Item = nil
		    }
			item.ItemIdStr = strconv.FormatInt(item.ItemId, 10)
			item.PItemIdStr = strconv.FormatInt(item.PItemId, 10)
			item.CreatedAtStr = item.CreatedAt.Format(consts.DATETIME_FORMAT)
			item.UpdatedAtStr = item.UpdatedAt.Format(consts.DATETIME_FORMAT)
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func GetItemIdArrBySubQuery(subquery map[string]string) ([]string, error) {
	skus := []*Sku{}
	idsArr := []string{}
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Sku))
	for k, v := range subquery {
		k = strings.Replace(k, ".", "__", -1)
		if ok := strings.Contains(v, "|"); ok {
		    valueArr := strings.Split(v, "|")
			qs = qs.Filter(k, valueArr)
		}else{
		    qs = qs.Filter(k, v)
		}	
	}
	if _, err := qs.RelatedSel("Item").All(&skus); err != nil {
	    return idsArr,err
	}
	for _, sku := range skus {
		sku.ItemId = fmt.Sprintf("%d", sku.Item.ItemId)
		idsArr = append(idsArr, sku.ItemId)
	}
	return idsArr, nil
}

func DeleteItemByItemId(id int64) (err error) {
	o := models.GetDefaultDB()
	v := Item{ItemId: id}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&v); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

func AddSku(m *Sku) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func AddMultiSkus(list []*Sku) (err error) {
	size := len(list)
	o := models.GetDefaultDB()
	if size > 1 {
	    _, err = o.InsertMulti(size, list) 
	}else if size == 1 {
	   _, err = o.Insert(list[0])
	} else {
	}
	return
}

func GetSkuBySkuId(id int64) (v *Sku, err error) {
	o := models.GetDefaultDB()
	v = &Sku{SkuId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetValidSkuBySkuId(id int64) (v *Sku, err error) {
	o := models.GetDefaultDB()
	v = &Sku{SkuId: id,StatusId:1}
	if err = o.Read(v,"SkuId","StatusId"); err == nil {
		return v, nil
	}
	return nil, err
}

func GetSkusBySkuIdArr(skuIdArr, fields []string,offset,limit int)([]*Sku, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Sku))
	cnt, err := qs.Count()
	var lists []*Sku
	qs = qs.Filter("sku_id__in", skuIdArr)
	qs = qs.Filter("status_id", 1)
       qs = qs.RelatedSel("Item")
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

func GetSkuByMulti(skuId int64, skuOuterId, barcode string) (sku *Sku, err error) {
	sku = &Sku{}
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Sku))
	if skuId > 0 {
	   qs = qs.Filter("sku_id", skuId)
	}
	if len(skuOuterId) > 0 {
	   qs = qs.Filter("sku_outer_id", skuOuterId)
	}
	if len(barcode) > 0 {
	   qs = qs.Filter("barcode", barcode)
	}
	err = qs.One(sku)
	return
}

func UpdateSkuBySkuId(m *Sku, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := Sku{SkuId: m.SkuId}
	if err = o.Read(&v); err == nil {
		_, err = o.Update(m, k...)
	}
	return
}

func UpdateSkuByOuterId(m *Sku, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := Sku{SkuOuterId: m.SkuOuterId}
	if err = o.Read(&v, "SkuOuterId"); err == nil {
		var num int64
		if num, err = o.Update(m, k...); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

func DeleteSkuBySkuId(id int64) (err error) {
	o := models.GetDefaultDB()
	v := Sku{SkuId: id}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&v); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

// 获取货品销售总数
func  GetItemSaleNum(partnerId int64, id int) int {
	var num int
	sql := fmt.Sprintf(`select sum(sale_num) from item where item_id=%d`, id)
	o := models.GetDefaultDB()
	_ = o.Raw(sql).QueryRow(&num)
	return num	
}

// 获取sku数量之和
func  GetOnSaleSkuStockNum(itemId int64, statusId int) int32 {
	var num int32
	sql := fmt.Sprintf(`select sum(sku_stocks) from sku where item_id=%d and status_id=%d`, itemId, statusId)
	o := models.GetDefaultDB()
	_ = o.Raw(sql).QueryRow(&num)
	return num	
}

func  CheckItemExistByFareId(fareId int64) bool {
	o := models.GetDefaultDB()
	exist := o.QueryTable(new(Item)).Filter("fare_id", fareId).Exist()
	return exist
}

func GetItemsByTagIds(categoryId,itemId,tagId,saleNum,price string,onShelves,offset,limit int) (cnt int64, items []*Item, err error) {
	sql := fmt.Sprintf(`select * from item where find_in_set(%s, tag_ids) {categoryId} {itemId} {shelves} {salenum} {price} limit %d,%d`, tagId, offset, limit)
	
	sqlCount := fmt.Sprintf(`select * from item where find_in_set(%s, tag_ids) {categoryId} {itemId} {shelves}`, tagId)
	
	if len(categoryId) > 0 {
		sql = strings.Replace(sql, "{categoryId}", fmt.Sprintf("and category_id = %s", categoryId), 1)
		sqlCount = strings.Replace(sqlCount, "{categoryId}", fmt.Sprintf("and category_id = %s", categoryId), 1)
	} else {
		sql = strings.Replace(sql, "{categoryId}", "", 1)
		sqlCount = strings.Replace(sqlCount, "{categoryId}", "", 1)
	}
	if len(itemId) > 0 {
		sql = strings.Replace(sql, "{itemId}", fmt.Sprintf("and item_id = %s", itemId), 1)
		sqlCount = strings.Replace(sqlCount, "{itemId}", fmt.Sprintf("and item_id = %s", itemId), 1)
	} else {
		sql = strings.Replace(sql, "{itemId}", "", 1)
		sqlCount = strings.Replace(sqlCount, "{itemId}", "", 1)
	}
	if onShelves > 0 {
		sql = strings.Replace(sql, "{shelves}", fmt.Sprintf("and on_shelves = %d", onShelves), 1)
		sqlCount = strings.Replace(sqlCount, "{shelves}", fmt.Sprintf("and on_shelves = %d", onShelves), 1)
	} else {
		sql = strings.Replace(sql, "{shelves}", "", 1)
		sqlCount = strings.Replace(sqlCount, "{shelves}", "", 1)
	}
	if saleNum == "desc" {
		sql = strings.Replace(sql, "{salenum}", "order by sale_num desc", 1)
	} else if saleNum == "asc" {
		sql = strings.Replace(sql, "{salenum}", "order by sale_num", 1)
	}else{
	    sql = strings.Replace(sql, "{salenum}", "", 1)
	}
	if price == "desc" {
		sql = strings.Replace(sql, "{price}", "order by price desc", 1)
	} else if price == "asc" {
		sql = strings.Replace(sql, "{price}", "order by price", 1)
	}else{
	    sql = strings.Replace(sql, "{price}", "", 1)
	}
	o := models.GetDefaultDB()
	//
	var itemstmp []*Item
    cnt, err = o.Raw(sqlCount).QueryRows(&itemstmp)
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

//
func GetItemIdsByPickpointId(pickpointId string) ([]string, error) {
	idsArr := []string{}
	items := []*Item{}
	sql := fmt.Sprintf(`select item_id from item where find_in_set(%s, delivery_addrs)`,pickpointId)
	o := models.GetDefaultDB()					
	_, err := o.Raw(sql).QueryRows(&items)
	if err != nil {
	   return idsArr, err
	}
	for _, item := range items {
		itemIdStr := fmt.Sprintf("%d", item.ItemId)
		idsArr = append(idsArr, itemIdStr)
	}
	return idsArr, nil
}
